package handler

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"video-comments/api/request"
	"video-comments/consts"
	"video-comments/global"
	"video-comments/internal/dao"
	"video-comments/internal/model"
	"video-comments/pkg"
)

func RegisterUser(c *gin.Context) {

	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		return
	}

	if req.Mobile == "" || req.Password == "" || req.Name == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOneByFile(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "手机号已被使用",
			"data": nil,
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		Name:     req.Name,
	}

	err = dao.AddFile(&user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": true,
	})
}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		return
	}

	if req.Mobile == "" || req.Password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOneByFile(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登录失败",
			"data": nil,
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id, 3*(24*time.Hour), consts.JWT_KEY)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登录成功",
		"data": token,
	})

	global.RDB.Set(context.Background(), fmt.Sprintf("%d", user.Id), user.Id, (time.Hour*24)*3)
}

func DeleteUser(c *gin.Context) {

}
